package cn.sx.yys.utils;

import cn.sx.yys.entity.EmailModel;
import cn.sx.yys.entity.ToModel;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 邮件发送工具
 *
 * @author YuanShuai
 */
public class SendMailUtils {
    /**
     * 发送普通邮件
     * @param email
     * @return
     */
    public static boolean sendMail(EmailModel email, ToModel to) {
        try {
            final Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", email.getHost());
            props.put("mail.user", email.getUsername());
            props.put("mail.password", email.getPassword());

            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            Session mailSession = Session.getInstance(props, authenticator);
            MimeMessage message = new MimeMessage(mailSession);
            String username = props.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            InternetAddress toAddress = new InternetAddress(to.getEmail());
            message.setRecipient(Message.RecipientType.TO, toAddress);

            message.setSubject(to.getTitle());

            message.setContent(to.getContent(), "text/html;charset=UTF-8");
            Transport.send(message);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) {
        EmailModel email = new EmailModel("smtp.163.com","apeblog@163.com","WIBXNBDDFSBKURFX");
        ToModel to = new ToModel("1603194187@qq.com");
        to.setTitle("测试邮件发送");
        to.setContent("这是一份测试邮件");
        long beginTime = System.currentTimeMillis();
        boolean b = SendMailUtils.sendMail(email, to);
        long endTime = System.currentTimeMillis();
        System.out.println(b);
        System.out.println(endTime-beginTime);
    }
}
